package com.vandzi.android.androidcode;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.vandzi.android.androidcode.model.Application;
import com.vandzi.android.androidcode.service.ActivitiesBringe;
import com.vandzi.android.androidcode.service.AndroidCodeService;
import com.vandzi.android.androidcode.service.InstalledApplicationsService;

public class ApplicationDetailsActivity extends Activity {

	private static final String TAG = "ApplicationDetailsActivity";
	private Application application;

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.application_details);

		// retrieve object passed from applications list
		application = (Application) ActivitiesBringe.getObject();
		if (application != null) {

			loadApplicationDetails();

			ImageView icon = (ImageView) findViewById(R.id.imageViewAppIcon);
			TextView name = (TextView) findViewById(R.id.textViewAppName);
			TextView author = (TextView) findViewById(R.id.textViewAppAuthorName);
			RatingBar rating = (RatingBar) findViewById(R.id.ratingBarAppRating);
			TextView applicationInstalled = (TextView) findViewById(R.id.textViewApplicationInstalled);

			icon.setImageDrawable(application.getImage());
			name.setText(application.getName());
			author.setText(application.getAuthor());
			rating.setRating(application.getAverageRating());

			if (InstalledApplicationsService.isApplicationInstalled(
					application.getPackageName(), getPackageManager())) {
				applicationInstalled
						.setText(getText(R.string.application_installed));
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.applications_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.refresh:
			loadApplicationDetails();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Display progress bar and load application details -> description...
	 */
	private void loadApplicationDetails() {

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				getApplicationDetails();
			}
		});
		thread.start();
		progressDialog = ProgressDialog.show(ApplicationDetailsActivity.this,
				"", getText(R.string.loading_application_details));
	}

	/**
	 * run this if app details are loaded
	 */
	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			if (application != null) {

				if (application.getApplicationDetails() != null) {
					TextView description = (TextView) findViewById(R.id.textViewDescription);
					String htmlText = application.getApplicationDetails()
							.getDescriptionInHtml();
					htmlText = htmlText.replace("</li>", "<br />");
					htmlText = htmlText.replace("<li>", "");

					description.setText(Html.fromHtml(htmlText));

					String votes = application.getApplicationDetails()
							.getVotes();
					String rating = application.getApplicationDetails()
							.getRating();

					RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBarAppRating);
					ratingBar.setRating(Float.parseFloat(rating));

					TextView ratingDecription = (TextView) findViewById(R.id.textViewRatingDescription);
					String ratingDescriptionText = String.format(
							getString(R.string.rating_description), rating,
							votes);
					ratingDecription.setText(ratingDescriptionText);

				}
				Button marketButton = (Button) findViewById(R.id.buttonMarket);
				marketButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

						try {
							Intent intent = new Intent(Intent.ACTION_VIEW);
							String marketUri = application.getMarketLink();
							// change from browser uri to Market app uri
							marketUri = marketUri.replace(
									"https://market.android.com/", "market://");
							intent.setData(Uri.parse(marketUri));
							startActivity(intent);
						} catch (Exception e) {
							// if market application is not available
							Log.i("MARKET_APP_MISSING", e.getMessage());
							Intent viewIntent = new Intent(
									"android.intent.action.VIEW", Uri
											.parse(application.getMarketLink()));
							startActivity(viewIntent);

						}

					}
				});

			}
			progressDialog.dismiss();
		}
	};

	private void getApplicationDetails() {

		try {
			application = AndroidCodeService
					.parseApplicationDetails(application);
			int i = 0;
			// try few time, because it crash sometimes
			while (application.getApplicationDetails() == null && i < 10) {
				i++;
				application = AndroidCodeService
						.parseApplicationDetails(application);

			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}

		runOnUiThread(returnRes);
	}

}
